from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from fastapi import HTTPException
from models.user import User
from schemas.user import UserCreate, UserRegister, UserLogin
import bcrypt

# 封装对模型的操作

def hash_password(password: str) -> str:
    """加密密码"""
    salt = bcrypt.gensalt()
    hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
    return hashed.decode('utf-8')

def verify_password(password: str, hashed_password: str) -> bool:
    """验证密码"""
    return bcrypt.checkpw(password.encode('utf-8'), hashed_password.encode('utf-8'))

# 用户注册
def register_user(db: Session, user: UserRegister):
    """用户注册"""
    # 检查用户名是否已存在
    existing_user = db.query(User).filter(User.username == user.username).first()
    if existing_user:
        raise HTTPException(status_code=400, detail="用户名已存在")
    
    # 检查手机号是否已存在
    existing_phone = db.query(User).filter(User.phone == user.phone).first()
    if existing_phone:
        raise HTTPException(status_code=400, detail="手机号已被注册")
    
    # 检查邮箱是否已存在
    existing_email = db.query(User).filter(User.email == user.email).first()
    if existing_email:
        raise HTTPException(status_code=400, detail="邮箱已被注册")
    
    # 加密密码
    hashed_password = hash_password(user.password)
    
    # 创建新用户
    db_user = User(
        username=user.username,
        phone=user.phone,
        email=user.email,
        password=hashed_password
    )
    
    try:
        db.add(db_user)
        db.commit()
        db.refresh(db_user)
        return {"message": "注册成功", "user_id": db_user.id}
    except IntegrityError:
        db.rollback()
        raise HTTPException(status_code=400, detail="注册失败，请检查输入信息")
    except SQLAlchemyError:
        db.rollback()
        raise HTTPException(status_code=500, detail="数据库错误")

# 用户登录
def login_user(db: Session, user: UserLogin):
    """用户登录 - 支持用户名、手机号或邮箱登录"""
    # 查找用户 - 支持用户名、手机号或邮箱
    db_user = db.query(User).filter(
        (User.username == user.username) | 
        (User.phone == user.username) | 
        (User.email == user.username)
    ).first()
    
    if not db_user:
        raise HTTPException(status_code=401, detail="用户名/手机号/邮箱或密码错误")
    
    # 验证密码
    if not verify_password(user.password, db_user.password):
        raise HTTPException(status_code=401, detail="用户名/手机号/邮箱或密码错误")
    
    return db_user

# 创建用户
def create_user(db: Session, user: UserCreate):
    db_user = User(phone=user.phone, email=user.email)
    db.add(db_user)
    try:
        db.commit()
        db.refresh(db_user)
        return db_user
    except IntegrityError:
        db.rollback()
        raise HTTPException(status_code=400, detail="Email already registered")
    except SQLAlchemyError:
        db.rollback()
        raise HTTPException(status_code=500, detail="Database error occurred")

# 获取指定用户
def get_user(db: Session, user_id: int):
    try:
        user = db.query(User).filter(User.id == user_id).first()
        if user is None:
            raise HTTPException(status_code=404, detail="User not found")
        return user
    except SQLAlchemyError:
        raise HTTPException(status_code=500, detail="Database error occurred")

# 获取用户列表
def get_users(db: Session, skip: int = 0, limit: int = 10):
    try:
        return db.query(User).offset(skip).limit(limit).all()
    except SQLAlchemyError:
        raise HTTPException(status_code=500, detail="Database error occurred")

# 更新用户
def update_user(db: Session, user_id: int, phone: str = None, email: str = None):
    """更新用户信息"""
    try:
        db_user = db.query(User).filter(User.id == user_id).first()
        if not db_user:
            raise HTTPException(status_code=404, detail="User not found")
        
        if phone is not None:
            # 检查手机号是否已被其他用户使用
            existing_phone = db.query(User).filter(User.phone == phone, User.id != user_id).first()
            if existing_phone:
                raise HTTPException(status_code=400, detail="手机号已被其他用户使用")
            db_user.phone = phone
            
        if email is not None:
            # 检查邮箱是否已被其他用户使用
            existing_email = db.query(User).filter(User.email == email, User.id != user_id).first()
            if existing_email:
                raise HTTPException(status_code=400, detail="邮箱已被其他用户使用")
            db_user.email = email
        
        db.commit()
        db.refresh(db_user)
        return db_user
    except HTTPException:
        raise
    except SQLAlchemyError:
        db.rollback()
        raise HTTPException(status_code=500, detail="Database error occurred")

# 删除用户
def delete_user(db: Session, user_id: int):
    try:
        db_user = db.query(User).filter(User.id == user_id).first()
        if db_user:
            # 先删除用户相关的统计数据
            from models.user_stats import UserStats
            stats_to_delete = db.query(UserStats).filter(UserStats.user_id == user_id).all()
            for stat in stats_to_delete:
                db.delete(stat)
            
            # 然后删除用户
            db.delete(db_user)
            db.commit()
            return True
        else:
            raise HTTPException(status_code=404, detail="User not found")
    except SQLAlchemyError as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"Database error occurred: {str(e)}")
